﻿using System;
using System.Collections.Generic;
using System.Linq;
using BabyShop.Site.Models;

namespace BabyShop.Site.Services
{
    public class ProductTypeService : BaseService<ProductType>
    {
        public ProductType GetProductTypeByGuid(Guid keyGuid)
        {
            return DataServices.ProductTypes.FirstOrDefault(p => p.ProductTypeGuid == keyGuid);
        }

        public IList<ProductType> GetAllProductTypes(bool immediateLoad = false)
        {

            return immediateLoad
                       ? DataServices.ProductTypes.Include("ChildProductTypes").Where(p => !p.CommonColumns.IsDelete)
                             .OrderBy(p => p.CommonColumns.LastModified).ToList()
                       : DataServices.ProductTypes.Where(p => !p.CommonColumns.IsDelete).ToList();
        }

        public IList<ProductType> GetTopLevelProductType()
        {
            return DataServices.ProductTypes.Where(p => !p.CommonColumns.IsDelete
                                                        && p.ParentGuid == null).OrderBy(
                                                            p => p.CommonColumns.LastModified).ToList();
        }

        public IList<ProductType> GetProductTypeTree(Guid productTypeGuid)
        {
            var productType = DataServices.ProductTypes.FirstOrDefault(p => !p.CommonColumns.IsDelete &&
                                                                            p.ProductTypeGuid == productTypeGuid);
            if (productType == null) return null;

            LinkedList<ProductType> productTypes = new LinkedList<ProductType>();
            productTypes.AddFirst(productType);
            var parentType = productType.ParentProductType;
            while (parentType != null) {
                productTypes.AddFirst(parentType);
                parentType = parentType.ParentProductType;
            }

            return productTypes.ToList();
        }

        public ProductType GetTheTopProductType(Guid productTypeGuid)
        {
            var productType =
                DataServices.ProductTypes.FirstOrDefault(
                    p => !p.CommonColumns.IsDelete && p.ProductTypeGuid == productTypeGuid);
            if(productType == null) return null;
            return !productType.ParentGuid.HasValue ? productType : GetTheTopProductType(productType.ParentGuid.Value);
        }
    }
}